package com.wanmait.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanmait.community.entity.*;
import com.wanmait.community.mapper.CarMapper;
import com.wanmait.community.mapper.MemberMapper;
import com.wanmait.community.mapper.ResidenceMapper;
import com.wanmait.community.service.UserService;
import com.wanmait.community.util.AjaxResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private CarMapper carMapper;
    @Resource
    private ResidenceMapper residenceMapper;

    @GetMapping("exitRoom/{id}")
    public AjaxResult exitRoom(@PathVariable Integer id){
        residenceMapper.deleteByPrimaryKey(id);
        return AjaxResult.success();
    }

    @GetMapping("getMember/{id}")
    private AjaxResult getmemeber(@PathVariable Integer id)
    {
        List<User> members = new ArrayList<>();
        List<Member> memberList = memberMapper.selectMembers(id);
        memberList.forEach(member -> {
            members.add(member.getMember());
        });
        return AjaxResult.success(members);
    }

    @GetMapping("getUserRoom/{id}")
    private  AjaxResult getUserRoom(@PathVariable Integer id){
        List<Residence> residences = residenceMapper.selectByUid(id);
        return AjaxResult.success(residences);
    }

    @GetMapping("getUserCar/{id}")
    private AjaxResult getUserCar(@PathVariable Integer id)
    {
        QueryWrapper<Car> wrapper = new QueryWrapper<Car>()
                .select("id","plate_num","color","brand")
                .eq("user_id",id);
        List<Car> carList = carMapper.selectList(wrapper);
        return AjaxResult.success(carList);
    }

    @GetMapping("list")
    private AjaxResult userlist(Para user){
        return userService.detailUsers(user);
    }

    @PostMapping("addResidence")
    private AjaxResult addResidence(@RequestBody Residence residence){
        residence.setUid(4);
        residenceMapper.insert(residence);
        return AjaxResult.success();
    }

    @PostMapping("addUser")
    private AjaxResult adduser(@RequestBody User user){
        if(user.getId()==null){
            userService.save(user);
        }
        else {
            userService.updateById(user);
        }

        return AjaxResult.success();
    }

    @GetMapping("delUser/{id}")
    public AjaxResult delUser(@PathVariable Integer id){
        userService.removeById(id);
        return AjaxResult.success();
    }
}
